package com.ruoyi.peach.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.peach.domain.CollectRecord;
import com.ruoyi.peach.domain.CollectTask;
import com.ruoyi.peach.service.ICollectRecordService;
import com.ruoyi.peach.service.ICollectTaskService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.peach.domain.RecordImg;
import com.ruoyi.peach.service.IRecordImgService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采集记录图片Controller
 * 
 * @author ruoyi
 * @date 2025-10-09
 */
@RestController
@RequestMapping("/peach/recordImg")
public class RecordImgController extends BaseController
{
    @Autowired
    private IRecordImgService recordImgService;

    @Autowired
    private ICollectRecordService collectRecordService;

    @Autowired
    private ICollectTaskService collectTaskService;

    /**
     * 查询采集记录图片列表
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:list')")
    @GetMapping("/list")
    public TableDataInfo list(RecordImg recordImg)
    {
        startPage();
        List<RecordImg> list = recordImgService.selectRecordImgList(recordImg);
        return getDataTable(list);
    }

    /**
     * 导出采集记录图片列表
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:export')")
    @Log(title = "采集记录图片", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RecordImg recordImg)
    {
        List<RecordImg> list = recordImgService.selectRecordImgList(recordImg);
        ExcelUtil<RecordImg> util = new ExcelUtil<RecordImg>(RecordImg.class);
        util.exportExcel(response, list, "采集记录图片数据");
    }

    /**
     * 获取采集记录图片详细信息
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(recordImgService.selectRecordImgById(id));
    }


    /**
     * 新增采集记录图片
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:add')")
    @Log(title = "采集记录图片", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RecordImg recordImg)
    {
        return toAjax(recordImgService.insertRecordImg(recordImg));
    }
    /**
     * 新增采集记录图片
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:add')")
    @Log(title = "上传采集记录图片", businessType = BusinessType.INSERT)
    @PostMapping("/uploadImg")
    public R uploadImg(@RequestBody RecordImg recordImg)
    {
        int i = recordImgService.uploadImg(recordImg);
        if(i == 1) return R.ok("上传成功");
        else return R.fail("上传失败");
    }

    /**
     * 修改采集记录图片
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:edit')")
    @Log(title = "采集记录图片", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RecordImg recordImg)
    {
        return toAjax(recordImgService.updateRecordImg(recordImg));
    }

    /**
     * 删除采集记录图片
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:remove')")
    @Log(title = "采集记录图片", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(recordImgService.deleteRecordImgByIds(ids));
    }

    /**
     * 根据记录ID下载图片压缩包
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:download')")
    @Log(title = "下载采集记录图片", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadZip/{recordId}")
    public void downloadZip(@PathVariable Long recordId, HttpServletResponse response) {
        try {
            logger.info("========== 开始下载记录ID: {} 的图片压缩包 ==========", recordId);

            // 查询采集记录获取任务ID
            CollectRecord record = collectRecordService.selectCollectRecordByRecordId(recordId);
            if (record == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"code\":404,\"msg\":\"未找到采集记录\"}");
                return;
            }

            // 查询任务获取任务名称
            String taskName = "未知任务";
            if (record.getTaskId() != null) {
                CollectTask task = collectTaskService.selectCollectTaskByTaskId(record.getTaskId());
                if (task != null && task.getTaskName() != null) {
                    taskName = task.getTaskName();
                }
            }
            logger.info("任务名称: {}", taskName);

            List<RecordImg> imgList = recordImgService.selectRecordImgByrecordId(recordId);
            logger.info("查询到图片记录数量: {}", imgList != null ? imgList.size() : 0);

            if (imgList == null || imgList.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"code\":404,\"msg\":\"未找到相关图片\"}");
                return;
            }

            response.setContentType("application/zip");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + taskName + "_" + recordId + ".zip");

            int fileCount = 0;
            try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                for (RecordImg img : imgList) {
                    String imgUrls = img.getImgUrls();
                    logger.info("记录ID: {}, 数据库URL: {}", img.getId(), imgUrls);

                    if (imgUrls == null || imgUrls.isEmpty()) {
                        logger.warn("记录ID: {} 的URL为空", img.getId());
                        continue;
                    }

                    // 分割多个图片URL（用逗号分隔）
                    String[] urlArray = imgUrls.split(",");
                    logger.info("记录ID: {}, 包含 {} 张图片", img.getId(), urlArray.length);

                    for (int i = 0; i < urlArray.length; i++) {
                        String imgUrl = urlArray[i].trim();

                        if (imgUrl.isEmpty()) continue;

                        // 转换为实际文件路径
                        String filePath = RuoYiConfig.getProfile() +
                                imgUrl.replaceFirst("^/profile", "");

                        logger.info("图片 {}-{}, URL: {}, 文件路径: {}",
                                img.getId(), i+1, imgUrl, filePath);

                        File file = new File(filePath);

                        if (file.exists() && file.isFile()) {
                            // 文件名：任务名称-序号.扩展名
                            String entryName = taskName + "-" +img.getRecordId()+"-"+ (fileCount + 1) +
                                    getFileExtension(imgUrl);
                            zos.putNextEntry(new ZipEntry(entryName));

                            try (FileInputStream fis = new FileInputStream(file)) {
                                byte[] buffer = new byte[8192];
                                int len;
                                while ((len = fis.read(buffer)) > 0) {
                                    zos.write(buffer, 0, len);
                                }
                            }

                            zos.closeEntry();
                            fileCount++;
                            logger.info("✓ 成功添加: {}, 大小: {} bytes",
                                    entryName, file.length());
                        } else {
                            logger.warn("✗ 文件不存在: {}", filePath);
                        }
                    }
                }
            }

            logger.info("========== 压缩完成，记录ID: {}, 成功: {} 个文件 ==========",
                    recordId, fileCount);

            if (fileCount == 0) {
                logger.warn("记录ID {} 没有有效的图片文件", recordId);
            }

        } catch (Exception e) {
            logger.error("下载压缩包失败，记录ID: {}", recordId, e);
            try {
                if (!response.isCommitted()) {
                    response.reset();
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write("{\"code\":500,\"msg\":\"下载失败: " + e.getMessage() + "\"}");
                }
            } catch (IOException ignored) {}
        }
    }


    /**
     * 批量下载多个记录的图片到一个压缩包
     */
    @PreAuthorize("@ss.hasPermi('peach:recordImg:download')")
    @Log(title = "批量下载采集记录图片", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadZipBatch")
    public void downloadZipBatch(@RequestParam String recordIds, HttpServletResponse response) {
        try {
            logger.info("========== 开始批量下载图片压缩包，记录IDs: {} ==========", recordIds);

            String[] recordIdArray = recordIds.split(",");
            if (recordIdArray.length == 0) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"code\":400,\"msg\":\"记录ID不能为空\"}");
                return;
            }

            // 获取第一个记录的任务名称作为压缩包名称
            Long firstRecordId = Long.parseLong(recordIdArray[0].trim());
            CollectRecord firstRecord = collectRecordService.selectCollectRecordByRecordId(firstRecordId);

            String taskName = "未知任务";
            if (firstRecord != null && firstRecord.getTaskId() != null) {
                CollectTask task = collectTaskService.selectCollectTaskByTaskId(firstRecord.getTaskId());
                if (task != null && task.getTaskName() != null) {
                    taskName = task.getTaskName();
                }
            }
            logger.info("任务名称: {}", taskName);

            // 收集所有记录的图片
            List<RecordImg> allImgList = new ArrayList<>();
            for (String recordIdStr : recordIdArray) {
                Long recordId = Long.parseLong(recordIdStr.trim());
                List<RecordImg> imgList = recordImgService.selectRecordImgByrecordId(recordId);
                if (imgList != null && !imgList.isEmpty()) {
                    allImgList.addAll(imgList);
                }
            }

            logger.info("总共查询到图片记录数量: {}", allImgList.size());

            if (allImgList.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"code\":404,\"msg\":\"未找到相关图片\"}");
                return;
            }

            response.setContentType("application/zip");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + taskName + "_merge.zip");

            int fileCount = 0;
            try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                for (RecordImg img : allImgList) {
                    String imgUrls = img.getImgUrls();

                    if (imgUrls == null || imgUrls.isEmpty()) {
                        continue;
                    }

                    String[] urlArray = imgUrls.split(",");

                    for (int i = 0; i < urlArray.length; i++) {
                        String imgUrl = urlArray[i].trim();

                        if (imgUrl.isEmpty()) continue;

                        String filePath = RuoYiConfig.getProfile() +
                                imgUrl.replaceFirst("^/profile", "");

                        File file = new File(filePath);

                        if (file.exists() && file.isFile()) {
                            // 文件名：任务名称-记录ID-序号.扩展名
                            String entryName = taskName +  "-" + (fileCount + 1) +
                                    getFileExtension(imgUrl);
                            zos.putNextEntry(new ZipEntry(entryName));

                            try (FileInputStream fis = new FileInputStream(file)) {
                                byte[] buffer = new byte[8192];
                                int len;
                                while ((len = fis.read(buffer)) > 0) {
                                    zos.write(buffer, 0, len);
                                }
                            }

                            zos.closeEntry();
                            fileCount++;
                            logger.info("✓ 成功添加: {}, 大小: {} bytes",
                                    entryName, file.length());
                        } else {
                            logger.warn("✗ 文件不存在: {}", filePath);
                        }
                    }
                }
            }

            logger.info("========== 批量压缩完成，成功: {} 个文件 ==========", fileCount);

        } catch (Exception e) {
            logger.error("批量下载压缩包失败，记录IDs: {}", recordIds, e);
            try {
                if (!response.isCommitted()) {
                    response.reset();
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write("{\"code\":500,\"msg\":\"下载失败: " + e.getMessage() + "\"}");
                }
            } catch (IOException ignored) {}
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String url) {
        int index = url.lastIndexOf(".");
        return index > 0 ? url.substring(index).split("\\?")[0] : ".jpg";
    }
}



